package com.business_clean.app.network

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.business_clean.app.config.ConstantMMVK
import com.business_clean.app.uitl.MMKVHelper
import com.business_clean.app.uitl.encodeSign
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.util.HashMap

/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val params: MutableMap<String, String> = HashMap<String, String>()
        if (request.method == "GET") {
            val paramNames = request.url.queryParameterNames
            for (paramName in paramNames) {
                val values = request.url.queryParameterValues(paramName)
                if (values != null && values.isNotEmpty()) {
                    params[paramName] = values[0].toString()
                }
            }
        } else if (request.method == "POST") {
            if (request.body is FormBody) {
                val body = request.body as FormBody?
                if (body != null) {
                    for (i in 0 until body.size) {
                        params[body.encodedName(i)] = body.value(i)
                    }
                }
            }
        }

        val timeMillis = "${System.currentTimeMillis() / 1000}"

        params["xmjz_time"] = timeMillis

        //添加共同的请求参数
        val httpUrl = request.url.newBuilder().addEncodedQueryParameter("xmjz_time", timeMillis).build()

        //公共参数处理
        var token = MMKVHelper.getString(ConstantMMVK.TOKEN)
        if (token == null) {
            token = ""
        }

        val sign = encodeSign(request.url.encodedPath.substring(1), token, params)

        //添加共同的请求头
        val requestNew =
            request.newBuilder().url(httpUrl)
                .addHeader("xmjztoken", token)
                .addHeader("xmjzsign", sign.toString())
                .addHeader("xmjzplatform", "android")
                .addHeader("xmjzversion", "" + AppUtils.getAppVersionName())
                .addHeader("xmjzdevice", "" + DeviceUtils.getManufacturer() + DeviceUtils.getModel())
                .build()
        return chain.proceed(requestNew)
    }

}